package com.sdk.springbootwebsocket.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    // 处理客户端发送到/app/chat的消息
    @MessageMapping("/chat")
    @SendTo("/topic/messages") // 将返回结果广播到/topic/messages
    public String handleMessage(String message) {
        System.out.println("Received: " + message);
        return "Echo: " + message;
    }

    // 处理客户端发送到/app/private的消息，向指定用户发送私有消息
    @MessageMapping("/private")
    public void sendPrivateMessage(@Header("userId") String userId, String message) {
        System.out.println("Received private message for user " + userId + ": " + message);
        messagingTemplate.convertAndSendToUser(userId, "/queue/private", "Private Echo: " + message);
    }
}